package com.wf.smartcomm.server.admin.action;

import java.util.HashMap;
import javax.annotation.Resource;

import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.YellowPage;
import com.wf.smartcomm.server.service.YellowPageService;
import com.wf.smartcomm.server.util.StringUtil;

@Controller
@Scope("prototype")
public class YellowAction extends BaseAction implements ModelDriven<YellowPage>{

	private YellowPage yp = new YellowPage();
	
	@Resource
	private YellowPageService ypServiceImpl;
	
	public void save() throws Exception{
		User manager = (User) session.getAttribute("loginUser");
		yp.setVillage(manager.getLoginVillage());
		if (!StringUtil.isEmpty(yp.getObjectId())) {
			ypServiceImpl.update(yp);
		} else {
			ypServiceImpl.save(yp);
		}
		printJsonData(200);
	}
	
	public String edit() throws Exception{
		yp = ypServiceImpl.get(yp.getObjectId());
		request.setAttribute("yp", yp);
		return "edit";
	}
	
	public void delete() throws Exception{
		ypServiceImpl.delete(yp);
		printJsonData(200);
	}
	
	public void list() throws Exception{
		String aoData = request.getParameter("aoData");
		String sEcho = "";
		String iDisplayStart = "";
		String iDisplayLength = "";
		String sSearch = "";
		User manager = (User) session.getAttribute("loginUser");
		JSONObject jo = new JSONObject(aoData);
		sEcho = jo.getString("sEcho");
		iDisplayStart = jo.getString("iDisplayStart");
		iDisplayLength = jo.getString("iDisplayLength");
		sSearch = jo.getString("sSearch");
		page.setBeginIndex(Integer.parseInt(iDisplayStart));
		page.setPageSize(Integer.parseInt(iDisplayLength));
		
		if (!StringUtil.isEmpty(sSearch)) {
			ypServiceImpl.query(manager.getLoginVillage(),sSearch,page);
		} else {
			ypServiceImpl.listByVillage(manager.getLoginVillage(), page);
		}
		
		int  initEcho = Integer.parseInt(sEcho)+1;
		int count = page.getTotalCount();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("iTotalRecords", count);
		dataMap.put("sEcho",initEcho);
		dataMap.put("iTotalDisplayRecords", count);
		dataMap.put("aaData", page.getDataList());
		printJsonData(outGson.toJson(dataMap));
	}
	
	@Override
	public YellowPage getModel() {
		return yp;
	}

}
